package com.mzba.easy.weibo.ui;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;

import com.google.gson.Gson;
import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.MainActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.AccessTokenEntry;
import com.mzba.easy.weibo.db.AccessTokenTable;
import com.mzba.easy.weibo.db.EmotionEntry;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.db.EmotionTable;
import com.mzba.easy.weibo.db.UserEntry;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.SSLSocketFactoryEx;
import com.mzba.easy.weibo.util.ServiceUtils;
import com.mzba.easy.weibo.util.StringUtil;
import com.mzba.easy.weibo.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class SplashActivity extends BasicActivity implements Callback {
	
	private Handler handler;
	public static final int login = 6;
	public static final int oauth_sucess = 1;
	public static final int oauth_error = 2;
	public static final int get_emotions = 3;
	public static final int oauth = 4;
	public static final int init = 5;
	
	public VerfierRecivier reciver;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppContext.setContext(this);
        handler = new Handler(this);
        setContentView(R.layout.activity_main);
        getSupportActionBar().hide();
        UICore.eventTask(this, this, init, "", null);
    }
    
    
    private void initedConfig() {
    	try {
        	AccessTokenTable table = new AccessTokenTable();
        	if (table.getAccessToken() != null) {
				if (Long.parseLong(table.getAccessToken().getExpires_in())
						+ table.getAccessToken().getOauthTime() < System.currentTimeMillis()) {
					handler.sendEmptyMessage(oauth);
					return;
				}
        		AppContext.getInstance().setAccess_token(table.getAccessToken().getAccess_token());
        		AppContext.getInstance().setUid(table.getAccessToken().getUid());
        		EmotionTable table2 = new EmotionTable();
    			List<EmotionEntry> entries = table2.getAllEmotions();
    			if (entries == null || entries.isEmpty()) {
    				handler.sendEmptyMessage(get_emotions);
    			} else {
    				AppContext.getInstance().setEmotionEntries(entries);
    				Map<String, String> faceMap = new HashMap<String, String>();
    				List<EmotionField> emotionFields = new ArrayList<EmotionField>();
    				for (EmotionEntry emotionEntry : entries) {
    					if (emotionEntry != null) {
    						faceMap.put(emotionEntry.getPhrase(), emotionEntry.getIcon());
    						EmotionField field = new EmotionField();
    						Field f;
    						try {
    							if (emotionEntry.getIcon() != null) {
    								String icon = emotionEntry.getIcon();
    								if (StringUtil.isNotBlank(icon)) {
    									f = (Field) R.drawable.class.getDeclaredField(icon);
    									if (f != null) {
    										field.setPhrase(emotionEntry.getPhrase());
    										field.setField(f);
    										emotionFields.add(field);
    									} 
    								}
    							}
    						} catch (SecurityException e) {
    							e.printStackTrace();
    						} catch (NoSuchFieldException e) {
    							e.printStackTrace();
    						} catch (IllegalArgumentException e) {
    							e.printStackTrace();
    						} 
    					}
    				}
    				AppContext.getInstance().setEmotionFields(emotionFields);
    				AppContext.getInstance().setFaceMap(faceMap);
    				handler.sendEmptyMessage(login);
    			}
        	} else {
        		handler.sendEmptyMessage(oauth);
        	}

		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    @Override
    public void execute(int mes, Object obj) {
    	switch (mes) {
		case oauth:
			bindSina(obj.toString());
			break;
		case get_emotions:
			try {
				EmotionTable table = new EmotionTable();
				table.saveLocalEmotions();
				List<EmotionEntry> entries = table.getAllEmotions();
				AppContext.getInstance().setEmotionEntries(entries);
				Map<String, String> faceMap = new HashMap<String, String>();
				List<EmotionField> emotionFields = new ArrayList<EmotionField>();
				for (EmotionEntry emotionEntry : entries) {
					if (emotionEntry != null) {
						faceMap.put(emotionEntry.getPhrase(), emotionEntry.getIcon());
						EmotionField field = new EmotionField();
						Field f;
						try {
							if (emotionEntry.getIcon() != null) {
								String icon = emotionEntry.getIcon();
								if (StringUtil.isNotBlank(icon)) {
									f = (Field) R.drawable.class.getDeclaredField(icon);
									if (f != null) {
										field.setPhrase(emotionEntry.getPhrase());
										field.setField(f);
										emotionFields.add(field);
									} 
								}
							}
						} catch (SecurityException e) {
							e.printStackTrace();
						} catch (NoSuchFieldException e) {
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} 
					}
				}
				AppContext.getInstance().setEmotionFields(emotionFields);
				AppContext.getInstance().setFaceMap(faceMap);
				handler.sendEmptyMessage(oauth_sucess);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case init:
			initedConfig();
			break;
		default:
			break;
		}
    	
    }


	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case oauth_sucess:
			destroyDialog();
			Intent loginIn = new Intent(this, MainActivity.class);
    		startActivity(loginIn);
    		finish();
			break;
		case oauth_error:
			onToast("认证失败！");
			break;
		case get_emotions:
			UICore.eventTask(this, this, get_emotions, "", null);
			break;
		case oauth:
			destroyDialog();
			Intent intent = new Intent();
			Bundle extras = new Bundle();
			extras.putString("url", AppContext.Authorize);
			intent.setClass(this, WebViewActivity.class);
			intent.putExtras(extras);
			startActivity(intent);
			
			IntentFilter filter = new IntentFilter();
			filter.addAction("oauth_verifier");
			reciver = new VerfierRecivier();
			registerReceiver(reciver, filter);
			break;
		case login:
			destroyDialog();
			Intent intentLogin = new Intent(this, MainActivity.class);
    		startActivity(intentLogin);
    		finish();
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (reciver != null) {
				unregisterReceiver(reciver);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class VerfierRecivier extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				final String code = bundle.getString("code");
				if (StringUtil.isNotBlank(code)) {
					UICore.eventTask(SplashActivity.this, SplashActivity.this, oauth, "", code);
				}
			}
		}
	}
	
	private void bindSina(String code) {
		String access_url = "https://api.weibo.com/oauth2/access_token";
		HttpClient request = getNewHttpClient();
		HttpPost httpPost;
		try {
			httpPost = new HttpPost(new URI(access_url));
			ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			params.add(new BasicNameValuePair("client_id", AppContext.App_Key));
			params.add(new BasicNameValuePair("client_secret", AppContext.App_Secret));
			params.add(new BasicNameValuePair("grant_type", "authorization_code"));
			params.add(new BasicNameValuePair("redirect_uri", AppContext.Callback));
			params.add(new BasicNameValuePair("code", code));
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			
			HttpResponse resposne = request.execute(httpPost);
			System.out.println(resposne.getStatusLine().getStatusCode());
			if (200 == resposne.getStatusLine().getStatusCode()) {
				InputStream inputStream = resposne.getEntity().getContent();
				String result = new String(ServiceUtils.readStream(inputStream));
				if (result != null) {
					Gson gson = new Gson();
					final AccessTokenEntry entry = gson.fromJson(result, AccessTokenEntry.class);
					entry.setOauthTime(System.currentTimeMillis());
					AccessTokenTable table = new AccessTokenTable();
					table.save(entry);
					AppContext.getInstance().setAccess_token(entry.getAccess_token());
					AppContext.getInstance().setUid(entry.getUid());
					String url = "https://api.weibo.com/2/users/show.json?access_token="+entry.getAccess_token() + "&uid="+entry.getUid();
					HttpGet httpGet;
					try {
						httpGet = new HttpGet(new URI(url));
						resposne = request.execute(httpGet);
						if (200 == resposne.getStatusLine().getStatusCode()) {
							inputStream = resposne.getEntity().getContent();
							result = new String(ServiceUtils.readStream(inputStream));
							UserEntry userEntry = gson.fromJson(result, UserEntry.class);
							if (userEntry != null) {
								ServiceUtils.downLoadImage(userEntry.getProfile_image_url(), AppContext.USERHEADICON, "avatar.png");
								SharedPreferences sp = getSharedPreferences("user_info", Activity.MODE_APPEND);
								Editor editor = sp.edit();
								editor.putString("name", userEntry.getScreen_name());
								editor.commit();
							}
						}
						EmotionTable emotionTable = new EmotionTable();
						emotionTable.saveLocalEmotions();
						List<EmotionEntry> entries = emotionTable.getAllEmotions();
						AppContext.getInstance().setEmotionEntries(entries);
						Map<String, String> faceMap = new HashMap<String, String>();
						List<EmotionField> emotionFields = new ArrayList<EmotionField>();
						for (EmotionEntry emotionEntry : entries) {
							if (emotionEntry != null) {
								faceMap.put(emotionEntry.getPhrase(), emotionEntry.getIcon());
								EmotionField field = new EmotionField();
								Field f;
								try {
									if (emotionEntry.getIcon() != null) {
										String icon = emotionEntry.getIcon();
										if (StringUtil.isNotBlank(icon)) {
											f = (Field) R.drawable.class.getDeclaredField(icon);
											if (f != null) {
												field.setPhrase(emotionEntry.getPhrase());
												field.setField(f);
												emotionFields.add(field);
											} 
										}
									}
								} catch (SecurityException e) {
									e.printStackTrace();
								} catch (NoSuchFieldException e) {
									e.printStackTrace();
								} catch (IllegalArgumentException e) {
									e.printStackTrace();
								} 
							}
						}
						AppContext.getInstance().setEmotionFields(emotionFields);
						AppContext.getInstance().setFaceMap(faceMap);
						handler.sendEmptyMessage(SplashActivity.oauth_sucess);
					} catch (URISyntaxException e) {
						e.printStackTrace();
					} catch (ClientProtocolException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} 
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public HttpClient getNewHttpClient() {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);
			SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));
			ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
			return new DefaultHttpClient(ccm, params);
		} catch (Exception e) {
			return new DefaultHttpClient();
		}
	}
	
}